<template>
  <div class="menu-content">


    <!-- 新增搜索卡片 -->
    <el-card class="card-container search-card" style="margin-bottom: 20px;">
      <div class="search-container">
        <!-- 将 justify="end" 修改为 justify="start" 实现靠左对齐 -->
        <el-row justify="start">
          <!-- 保持列宽比例和搜索框宽度 -->
          <el-col :span="10">
            <!-- 添加@input和@clear事件 -->
            <el-input v-model="searchParams.keyword" placeholder="请输入搜索的设备ID" class="search-input" @input="handleSearch"
              @clear="handleSearch">
            </el-input>
          </el-col>
          <!-- 保持按钮列宽度和间距 -->
          <el-col :span="4" style="margin-left: 10px;">
            <el-button type="primary" class="search-button" @click="handleSearch">搜索</el-button>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 原有表格卡片容器 -->
    <el-card class="card-container table-card">
      <!-- 中文化分页表格 -->
      <el-table :data="paginatedRepairTasks" stripe border class="custom-table rounded-table" v-loading="loading">
        <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
        <el-table-column prop="equipmentId" label="设备ID" align="center"></el-table-column>
        <el-table-column prop="equipmentName" label="设备名称" align="center"></el-table-column>
        <el-table-column prop="remark" label="维修备注" align="center">
          <template #default="scope">
            <el-button type="text" @click="openRemarkDialog(scope.row.remark)">查看详情</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="statusText" label="状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 2 ? 'success' : scope.row.status === 1 ? 'info' : 'warning'">{{
              scope.row.statusText }}</el-tag>
          </template>
        </el-table-column>
        <!-- 状态修改列 -->
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <!-- 标记为已完成按钮 - 待处理状态禁用 -->
            <el-button type="primary" size="small" @click="handleComplete(scope.row)"
              :loading="scope.row.completeLoading" :disabled="scope.row.status === 0" style="margin-right: 5px;">
              标记为已完成
            </el-button>
            <!-- 标记为维修中按钮 - 维修中状态禁用 -->
            <el-button type="primary" size="small" @click="handleInProgress(scope.row)"
              :loading="scope.row.inProgressLoading" :disabled="scope.row.status === 1">
              标记为维修中
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 中文化分页控件 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
          layout="total, prev, pager, next, jumper" :prev-text="'上一页'" :next-text="'下一页'"
          @current-change="handleCurrentChange">
          <template #format-total="{ total }">
            总计 {{ total }} 条
          </template>
        </el-pagination>
      </div>
    </el-card>

    <!-- 维修备注详情弹窗 -->
    <el-dialog v-model="showRemarkDialog" title="维修备注详情" width="500px" :close-on-click-modal="false">
      <div class="remark-content">
        <p v-if="!currentRemark" class="empty-remark">暂无维修备注信息</p>
        <pre v-else>{{ currentRemark }}</pre> <!-- 展示后端返回的remark原始格式 -->
      </div>
      <template #footer>
        <el-button @click="showRemarkDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue';
import { Search } from '@element-plus/icons-vue';
// 从request导入axios实例
import request from '@/utils/request';
import { ElMessage, ElTag } from 'element-plus';

export default {
  name: 'RepairTasks',
  components: { Search, ElTag },
  setup() {
    // 修复：正确定义searchParams
    const searchParams = ref({
      keyword: ''
    });

    // 状态管理
    const repairTasks = ref([]);
    const allRepairTasks = ref([]); // 新增：存储所有数据用于前端分页
    const loading = ref(false);
    const showRemarkDialog = ref(false);
    const currentRemark = ref('');

    // 分页控制
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    const remarkDialogVisible = ref(false);

    // 合并后的搜索参数
    // 删除搜索参数对象
    // const searchParams = ref({
    //   keyword: '' // 单个搜索关键词
    // });

    // 状态码映射表（根据API文档定义）
    const statusMap = {
      0: '待处理',
      1: '维修中',
      2: '已完成'
    };

    // 获取维修任务数据 - 已移除所有后端分页参数
    const fetchRepairTasks = async () => {
      loading.value = true;
      try {
        const response = await request.get('/users/getMyRepair', {
          params: {}
        });
        if (response.code === 200) {
          // 严格按照响应参数结构处理数据
          const tasks = Array.isArray(response.data) ? response.data : [];
          allRepairTasks.value = tasks.map(task => ({
            ...task,
            // 仅保留状态文本映射
            statusText: statusMap[task.status] || '未知状态'
          }));
          // 删除搜索方法调用
          // handleSearch();
          // 直接赋值所有数据
          repairTasks.value = allRepairTasks.value;
          total.value = allRepairTasks.value.length;
        } else {
          ElMessage.error(response.msg || '获取数据失败');
        }
      } catch (error) {
        console.error('获取维修任务失败:', error);
        ElMessage.error('获取数据失败，请重试');
      } finally {
        loading.value = false;
      }
    };

    // 实时查询处理 - 修改为前端过滤
    const handleSearch = () => {
      currentPage.value = 1;
      let filtered = [...allRepairTasks.value];
      // 优化搜索条件判断，确保空值时显示所有数据
      if (searchParams.value.keyword && searchParams.value.keyword.trim()) {
        const keyword = searchParams.value.keyword.trim();
        // 仅保留设备ID字段的精确搜索
        filtered = filtered.filter(task =>
          task.equipmentId && task.equipmentId.toString() === keyword
        );
      }
      total.value = filtered.length;
      repairTasks.value = filtered;
    };

    // 分页数据计算 - 实现前端分页逻辑
    const paginatedRepairTasks = computed(() => {
      const startIndex = (currentPage.value - 1) * pageSize.value;
      return repairTasks.value.slice(startIndex, startIndex + pageSize.value);
    });

    // 分页事件处理 - 已删除后端分页API调用
    const handleCurrentChange = (val) => {
      currentPage.value = val;
      // 仅更新页码，不触发后端请求
    };

    // 打开备注详情
    // 打开备注详情
    const openRemarkDialog = (remark) => {
      currentRemark.value = remark || ''; // 将后端返回的remark内容赋值给弹窗变量
      showRemarkDialog.value = true; // 显示弹窗
    };

    // 状态修改处理 - 拆分为两个独立方法
    const handleComplete = async (row) => {
      row.completeLoading = true;
      try {
        // 按照接口文档实现POST请求
        const response = await request.post('/users/completeRepair', {
          repairId: parseInt(row.equipmentId),
          status: 1,
          remark: '维修任务已完成',
          userId: parseInt(localStorage.getItem('userId') || sessionStorage.getItem('userId')) // ✅ 从本地存储获取当前用户ID
        });
        // 接口文档规定成功code为0
        if (response.code === 200) {
          ElMessage.success('已成功标记为完成状态');
          fetchRepairTasks(); // 刷新任务列表
        } else {
          ElMessage.error(response.msg || '操作失败，请重试');
        }
      } catch (error) {
        console.error('标记为完成失败:', error);
        ElMessage.error('网络异常，请稍后重试');
      } finally {
        row.completeLoading = false;
      }
    };

    const handleInProgress = async (row) => {
      row.inProgressLoading = true;
      try {
        // 修复参数名和响应码检查
        const response = await request.get('/users/changeRepairStatus', {
          params: {
            repairId: parseInt(row.equipmentId)// 确保参数名小写且类型为整数
          }
        });
        // 接口文档显示成功code为0
        if (response.code === 200) {
          ElMessage.success('已标记为维修中');
          fetchRepairTasks(); // 刷新列表
        } else {
          ElMessage.error(response.msg || '操作失败，请重试');
        }
      } catch (error) {
        console.error('标记为维修中失败:', error);
        ElMessage.error('操作失败，请重试');
      } finally {
        row.inProgressLoading = false;
      }
    };

    // 页面加载时获取数据
    onMounted(() => {
      fetchRepairTasks();
    });

    return {
      loading,
      currentPage,
      pageSize,
      total,
      paginatedRepairTasks,
      showRemarkDialog,
      currentRemark,
      handleCurrentChange,
      openRemarkDialog,
      handleComplete,
      handleInProgress,
      // 添加缺失的导出变量
      searchParams,
      handleSearch
    };
  }
};
</script>

<style scoped>
/* 修改卡片容器基础样式 - 移除宽度定义 */
.card-container {
  margin: 0 auto 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 搜索卡片单独定义宽度 */
.search-card {
  width: 90%;
  padding: 20px;
}

/* 表格卡片单独定义宽度 */
.table-card {
  width: 90%;
  padding: 20px;
}

/* 修改分页容器样式 */
.pagination-container {
  margin-top: 20px;
  text-align: left;
  /* 改为左对齐 */
  padding-left: 20px;
  /* 添加左侧内边距与表格对齐 */
}

/* 表头样式 - 保持不变 */
::v-deep .custom-table .el-table__header-wrapper .el-table__header {
  background-color: #1890ff !important;
}

::v-deep .custom-table .el-table__header th {
  background-color: #1890ff !important;
  color: #fff !important;
  border-bottom: 2px solid white !important;
}

/* 表格行基础样式 */
::v-deep .custom-table .el-table__body-wrapper .el-table__row {
  transition: all 0.2s ease;
  position: relative;
}

/* 表格行悬浮效果 - 三级选择器保障 */
/* 第一级：表格行悬浮基础样式 */
::v-deep .custom-table .el-table__body-wrapper .el-table__row:hover {
  transform: scale(1.01);
  transform-origin: center left;
  background-color: #1890ff !important;
  color: #fff !important;
  font-size: 15px;
  z-index: 10;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  padding: 0 5px;
}

/* 第二级：增强特异性 */
::v-deep .custom-table .el-table__body .el-table__row:hover {
  background-color: #1890ff !important;
  color: #fff !important;
}

/* 第三级：单元格样式保障 */
::v-deep .el-table__body tr.el-table__row:hover>td {
  background-color: #1890ff !important;
  color: #fff !important;
}

/* 悬浮行中的文本按钮文字变白 */
::v-deep .el-table__row:hover .el-button--text {
  color: #fff !important;
}

/* 表格圆角样式 */
::v-deep .rounded-table {
  border-radius: 12px !important;
  overflow: hidden !important;
  border: none !important;
}

/* 确保表格有足够宽度容纳放大后的内容 */
::v-deep .el-table__body {
  width: 100% !important;
}

/* 确保没有其他样式干扰 */
::v-deep .custom-table .el-table__cell {
  background-color: transparent !important;
}

/* 表格样式调整 */
::v-deep .custom-table {
  min-height: 400px;
  /* 设置最小高度确保留白 */
  width: 100% !important;
  /* 确保表格宽度100% */
}
</style>

/* 修改搜索卡片样式 */
.search-card {
width: 90%; /* 与表格卡片宽度保持一致 */
margin: 0 auto 20px; /* 居中对齐并添加底部间距 */
padding: 20px;
}

.search-container {
width: 100%;
}
